package promotion

import (
	// "bp/cache"
	"bp/conf"
	"bp/db"

	// "bgs/grpc/client"
	"bp/internal/nsqserver/producer"
	"bp/internal/service/com"
	"bp/internal/service/entity"
	"bp/internal/twirpex"
	"go.uber.org/zap"

	// "bp/internal/util"
	messageGrpc "bp/rpc/gen/shared/message"
	cronGrpc "bp/rpc/gen/webapi/cron"
	"context"

	"github.com/go-chi/chi"
	"github.com/golang/protobuf/ptypes/empty"
)

type CronWebApiImp struct {
	dao       *db.PgDao
	slog      *zap.SugaredLogger
	vars      *conf.VarsSection
	pub       *producer.NsqProducerProxy
	entityHub *entity.EntityHub
	comHub    *com.ComHub
	// cacher *cache.Adapter
	cronGrpc.CronOpService
}

// NewCronWebApi initialization
func New(
	slog *zap.SugaredLogger,
	pgdao *db.PgDao,
	vars *conf.VarsSection,
	pub *producer.NsqProducerProxy,
	entityHub *entity.EntityHub,
	comHub    *com.ComHub,
	// adp *cache.Adapter,
) (ws *CronWebApiImp) {
	ws = &CronWebApiImp{
		dao:       pgdao,
		slog:      slog.With("module", "CronWebApi"),
		vars:      vars,
		pub:       pub,
		entityHub: entityHub,
		// cacher:           adp,
	}
	return
}

const (
	EntityName                             string = "cron"
	PingCronMethod                         string = "/cron/ping/exec"
	ExpireCouponsMethod                    string = "/cron/expire/coupons"           // POST
	ExpireMemberCouponsMethod              string = "/cron/expire/member_coupons"    // POST
	ExpirePromotionsMethod                 string = "/cron/expire/promotions"        // POST
	PublishNsqsMethod                      string = "/cron/publish/nsqs"             // POST
	HandleCompensationSubscribedNsqsMethod string = "/cron/compensation/handle/nsqs" // POST
)

// RegisterToWeb 将部分grpc方法注册到web
func (s *CronWebApiImp) RegisterToWeb(r chi.Router) {
	cronRT := twirpex.NewSingleTwirpServerProxy(cronGrpc.NewCronOpServiceServer(s))

	r.Group(func(r chi.Router) {
		r.Get(PingCronMethod, cronRT.Handle("PingCron"))
		r.Post(ExpireCouponsMethod, cronRT.Handle("ExpireCoupons"))
		r.Post(ExpireMemberCouponsMethod, cronRT.Handle("ExpireMemberCoupons"))
		r.Post(ExpirePromotionsMethod, cronRT.Handle("ExpirePromotions"))
		r.Post(PublishNsqsMethod, cronRT.Handle("PublishNsqs"))
		r.Post(HandleCompensationSubscribedNsqsMethod, cronRT.Handle("HandleCompensationSubscribedNsqs"))
	})
}

func (s *CronWebApiImp) PingCron(ctx context.Context, _ *empty.Empty) (res *messageGrpc.PingRes, err error) {
	res = &messageGrpc.PingRes{
		Msg: "ok",
	}
	return
}
